/**
 * Generate code from /{{projectName}}-core/src/main/java/{{packageName}}/core/{{modules}}/service/impl/Abstract{{entities@SQL}}Service.java.hbs
 */
package cn.ibizlab.core.ad.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.util.*;
import cn.ibizlab.util.errors.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.core.ad.domain.SysOrganization;
import cn.ibizlab.core.ad.filter.SysOrganizationSearchContext;
import cn.ibizlab.core.ad.service.SysOrganizationService;
import cn.ibizlab.core.ad.mapper.SysOrganizationMapper;
import cn.ibizlab.util.enums.Entities;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cn.ibizlab.core.ad.domain.SysDepartment;
import cn.ibizlab.core.ad.service.SysDepartmentService;
import cn.ibizlab.core.ad.domain.SysPerson;
import cn.ibizlab.core.ad.service.SysPersonService;
import cn.ibizlab.core.ad.domain.SysOrganizationalRole;
import cn.ibizlab.core.ad.service.SysOrganizationalRoleService;
import cn.ibizlab.core.ad.domain.SysOrganizationalUnit;
import cn.ibizlab.core.ad.service.SysOrganizationalUnitService;

/**
 * 实体[组织机构] 服务对象接口实现
 *
 * @author generator
 */
@Slf4j
public abstract class AbstractSysOrganizationService extends ServiceImpl<SysOrganizationMapper,SysOrganization> implements SysOrganizationService {

    @Autowired
    @Lazy
    protected SysDepartmentService sysDepartmentService;

    @Autowired
    @Lazy
    protected SysPersonService sysPersonService;

    @Autowired
    @Lazy
    protected SysOrganizationalRoleService sysOrganizationalRoleService;

    @Autowired
    @Lazy
    protected SysOrganizationalUnitService sysOrganizationalUnitService;

    @Autowired
    @Lazy
    protected SysOrganizationService sysOrganizationService;

    @Autowired
    @Lazy
    protected cn.ibizlab.core.ad.mapping.SysOrganizationInheritMapping sysOrganizationInheritMapping;

    protected int batchSize = 500;

    public SysOrganization get(SysOrganization et) {
        SysOrganization rt = this.baseMapper.selectEntity(et);
        if(rt == null)
            throw new NotFoundException("数据不存在",Entities.SYS_ORGANIZATION.toString(),et.getId());
        rt.copyTo(et,true);
        //设置 [部门]
        getDepartments(et);
        return et;
    }

    public List<SysOrganization> getByEntities(List<SysOrganization> entities) {
        return this.baseMapper.selectEntities(entities);
    }

    public void fillParentData(SysOrganization et) {
        if(Entities.SYS_ORGANIZATION.equals(et.getContextParentEntity()) && et.getContextParentKey()!=null) {
            et.setParentId((String)et.getContextParentKey());
            SysOrganization sysOrganization = et.getParent();
            if(sysOrganization == null) {
                sysOrganization = sysOrganizationService.getById(et.getParentId());
                et.setParent(sysOrganization);
            }
            if(!ObjectUtils.isEmpty(sysOrganization)) {
                et.setParentId(sysOrganization.getId());
                et.setParentName(sysOrganization.getOrganizationName());
            }
        }
    }

    public SysOrganization getDraft(SysOrganization et) {
        fillParentData(et);
        return et;
    }

    public Integer checkKey(SysOrganization et) {
        return (!ObjectUtils.isEmpty(et.getId()) && this.count(Wrappers.<SysOrganization>lambdaQuery().eq(SysOrganization::getId, et.getId()))>0)?1:0;
    }

    @Override
    @Transactional
    public boolean create(SysOrganization et) {
        fillParentData(et);
        if(this.baseMapper.insert(et) < 1)
            return false;
        sysDepartmentService.saveByOrganization(et,et.getDepartments());
        get(et);
        return true;
    }

    @Transactional
    public boolean createBatch(List<SysOrganization> list) {
        list.forEach(et->getSelf().create(et));
        return true;
    }

    @Transactional
    public boolean update(SysOrganization et) {
        UpdateWrapper<SysOrganization> qw = et.getUpdateWrapper(true);
        qw.eq("id", et.getId());
        if(!update(et, qw))
            return false;
        sysDepartmentService.saveByOrganization(et,et.getDepartments());
        get(et);
        return true;
    }

    @Transactional
    public boolean updateBatch(List<SysOrganization> list) {
        list.forEach(et->getSelf().update(et));
        return true;
    }

    @Override
    @Transactional
    public boolean save(SysOrganization et) {
        if(checkKey(et) > 0)
            return getSelf().update(et);
        else
            return getSelf().create(et);
    }

    @Transactional
    public boolean saveBatch(List<SysOrganization> list) {
        if(ObjectUtils.isEmpty(list))
            return true;
        Map<String,SysOrganization> before = getByEntities(list).stream().collect(Collectors.toMap(SysOrganization::getId,e->e));
        List<SysOrganization> create = new ArrayList<>();
        List<SysOrganization> update = new ArrayList<>();
        list.forEach(sub->{
            if(!ObjectUtils.isEmpty(sub.getId()) && before.containsKey(sub.getId()))
                update.add(sub);
            else
                create.add(sub);
        });
        if(!update.isEmpty())
            update.forEach(item->this.getSelf().update(item));
        if(!create.isEmpty() && !getSelf().createBatch(create))
            return false;
        else
            return true;
    }

    @Transactional
    public boolean remove(SysOrganization et) {
        String key = et.getId();
        if(!ObjectUtils.isEmpty(sysDepartmentService.findByOrganizationId(key)))
            throw new BadRequestAlertException("删除数据失败，当前数据存在关系实体[sysDepartment]数据，无法删除!",Entities.SYS_ORGANIZATION.toString(),key);
        if(!ObjectUtils.isEmpty(sysOrganizationService.findByParentId(key)))
            throw new BadRequestAlertException("删除数据失败，当前数据存在关系实体[sysOrganization]数据，无法删除!",Entities.SYS_ORGANIZATION.toString(),key);
        if(!ObjectUtils.isEmpty(sysPersonService.findByOrganizationId(key)))
            throw new BadRequestAlertException("删除数据失败，当前数据存在关系实体[sysPerson]数据，无法删除!",Entities.SYS_ORGANIZATION.toString(),key);
        if(!remove(Wrappers.<SysOrganization>lambdaQuery().eq(SysOrganization::getId, et.getId())))
            return false;
        return true;
    }

    @Transactional
    public boolean removeByEntities(List<SysOrganization> entities) {
        for (SysOrganization et : entities)
            if(!getSelf().remove(et))
                return false;
        return true;
    }

    public Page<SysOrganization> searchDefault(SysOrganizationSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SysOrganization> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        List<SysOrganization> list = pages.getRecords();
        return new PageImpl<>(list, context.getPageable(), pages.getTotal());
    }

    public List<SysOrganization> listDefault(SysOrganizationSearchContext context) {
        List<SysOrganization> list = baseMapper.listDefault(context,context.getSelectCond());
        return list;
    }

    public Page<SysOrganization> searchMaintenance(SysOrganizationSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SysOrganization> pages=baseMapper.searchMaintenance(context.getPages(),context,context.getSelectCond());
        List<SysOrganization> list = pages.getRecords();
        return new PageImpl<>(list, context.getPageable(), pages.getTotal());
    }

    public List<SysOrganization> listMaintenance(SysOrganizationSearchContext context) {
        List<SysOrganization> list = baseMapper.listMaintenance(context,context.getSelectCond());
        return list;
    }

    public Page<SysOrganization> searchMyOrg(SysOrganizationSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SysOrganization> pages=baseMapper.searchMyOrg(context.getPages(),context,context.getSelectCond());
        List<SysOrganization> list = pages.getRecords();
        return new PageImpl<>(list, context.getPageable(), pages.getTotal());
    }

    public List<SysOrganization> listMyOrg(SysOrganizationSearchContext context) {
        List<SysOrganization> list = baseMapper.listMyOrg(context,context.getSelectCond());
        return list;
    }

    public Page<SysOrganization> searchNav(SysOrganizationSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SysOrganization> pages=baseMapper.searchNav(context.getPages(),context,context.getSelectCond());
        List<SysOrganization> list = pages.getRecords();
        return new PageImpl<>(list, context.getPageable(), pages.getTotal());
    }

    public List<SysOrganization> listNav(SysOrganizationSearchContext context) {
        List<SysOrganization> list = baseMapper.listNav(context,context.getSelectCond());
        return list;
    }

    public Page<SysOrganization> searchParentOrg(SysOrganizationSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SysOrganization> pages=baseMapper.searchParentOrg(context.getPages(),context,context.getSelectCond());
        List<SysOrganization> list = pages.getRecords();
        return new PageImpl<>(list, context.getPageable(), pages.getTotal());
    }

    public List<SysOrganization> listParentOrg(SysOrganizationSearchContext context) {
        List<SysOrganization> list = baseMapper.listParentOrg(context,context.getSelectCond());
        return list;
    }

    public List<SysOrganization> findByParentId(List<String> parentIds) {
        List<SysOrganization> list = baseMapper.findByParentId(parentIds);
        if(!ObjectUtils.isEmpty(list))
            sysDepartmentService.findByOrganizationId(list.stream().map(e->e.getId()).collect(Collectors.toList()))
                .stream().collect(Collectors.groupingBy(e->e.getOrganizationId())).entrySet().forEach(sub->list.stream().filter(item->item.getId().equals(sub.getKey())).findFirst().ifPresent(item->item.setDepartments(sub.getValue())));
        return list;
    }

    public boolean removeByParentId(String parentId) {
        List<String> ids = baseMapper.findByParentId(Arrays.asList(parentId)).stream().map(e->e.getId()).collect(Collectors.toList());
        if(!ObjectUtils.isEmpty(ids))
            return this.removeBatch(ids);
        else
            return true;
    }

    public boolean resetByParentId(String parentId) {
        return this.update(Wrappers.<SysOrganization>lambdaUpdate().eq(SysOrganization::getParentId,parentId));
    }

    public boolean saveByParent(SysOrganization sysOrganization,List<SysOrganization> list) {
        if(list==null)
            return true;
        Map<String,SysOrganization> before = findByParentId(sysOrganization.getId()).stream().collect(Collectors.toMap(SysOrganization::getId,e->e));
        List<SysOrganization> update = new ArrayList<>();
        List<SysOrganization> create = new ArrayList<>();

        for(SysOrganization sub:list) {
            sub.setParentId(sysOrganization.getId());
            sub.setParent(sysOrganization);
            if(!ObjectUtils.isEmpty(sub.getId())&&before.containsKey(sub.getId())) {
                before.remove(sub.getId());
                update.add(sub);
            }
            else
                create.add(sub);
        }
        if(!update.isEmpty())
            update.forEach(item->this.getSelf().update(item));
        if(!create.isEmpty() && !getSelf().createBatch(create))
            return false;
        else if(!before.isEmpty() && !getSelf().removeBatch(before.keySet()))
            return false;
        else
            return true;
    }

    @Override
    public List<SysDepartment> getDepartments(SysOrganization et) {
        List<SysDepartment> list = sysDepartmentService.findByOrganizationId(et.getId());
        et.setDepartments(list);
        return list;
    }

    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith(SqlMethod.INSERT_ONE.getMethod())) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith(SqlMethod.UPDATE.getMethod())) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith(SqlMethod.DELETE.getMethod())) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    protected Class currentMapperClass() {
        return SysOrganizationMapper.class;
    }

    @Override
    protected Class currentModelClass() {
        return SysOrganization.class;
    }
}